package at.fhj.itm11.forum.controller;

import java.io.Serializable;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import at.fhj.itm11.forum.beans.AuthenticationBean;
import at.fhj.itm11.forum.model.Comment;
import at.fhj.itm11.forum.model.Post;
import at.fhj.itm11.forum.model.User;
import at.fhj.itm11.forum.service.CommentRegistration;
import at.fhj.itm11.forum.util.ForumConstants;

@ManagedBean
@RequestScoped
public class CommentController implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1204607967079731162L;

	@Inject
	private CommentRegistration commentRegistration;
	private Comment newComment;
	private HttpSession session;
	
	@Inject
	private AuthenticationBean authBean;
	
	@PostConstruct
	public void initNewComment() {
		newComment = new Comment();
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		session = (HttpSession) externalContext.getSession(true);
	}
	
	public void savePostToSession(Post p) {
		session.setAttribute(ForumConstants.SESSION_CURRENT_POST, p);
	}

	public void register() {
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			
			if(newComment.getText() == null || "".equals(newComment.getText())) {
			context.addMessage("reg:text", new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Creation failed", "Text must not be empty!"));
			}
			else {
				newComment.setDate(new Date());
				Post post = (Post) session.getAttribute(ForumConstants.SESSION_CURRENT_POST);
				newComment.setPost(post);
				newComment.setUser((User) authBean.getCurrentUser());
				commentRegistration.register(newComment);
				newComment = null;
			}
			
		} catch (Exception e) {
			String errorMessage = getRootErrorMessage(e);
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
					errorMessage, "Creation unsuccessful"));
		}
	}
	

	private String getRootErrorMessage(Exception e) {
		// Default to general error message that registration failed.
		String errorMessage = "Registration failed. See server log for more information";
		if (e == null) {
			// This shouldn't happen, but return the default messages
			return errorMessage;
		}

		// Start with the exception and recurse to find the root cause
		Throwable t = e;
		while (t != null) {
			// Get the message from the Throwable class instance
			errorMessage = t.getLocalizedMessage();
			t = t.getCause();
		}
		// This is the root cause message
		return errorMessage;
	}

	public Comment getNewComment() {
		return newComment;
	}

	public void setNewComment(Comment newComment) {
		this.newComment = newComment;
	}
}
